package woa.binarysearch;

import java.util.Arrays;

/**
 * 在排序数组中查找元素的第一个和最后一个位置
 * 给定一个按照升序排列的整数数组 nums，和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
 * 如果数组中不存在目标值 target，返回 [-1, -1]。
 *
 * 输入：nums = [5,7,7,8,8,10], target = 8
 * 输出：[3,4]
 *
 * @author wangpeng
 * @date 2021/12/20
 */
public class SearchRange {

    public static int[] searchRange(int[] nums, int target) {
        int[] rs = new int[]{-1, -1};
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return helper(nums, target, mid, mid);
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        return rs;
    }

    public static int[] helper(int[] nums, int target, int left, int right) {
        int[] rs = new int[]{-1, -1};
        while (rs[0] == -1 || rs[1] == -1) {
            if (left > 0 && nums[left] == target && nums[left - 1] == target) {
                left = left - 1;
            } else {
                rs[0] = left;
            }
            if (right < nums.length - 1 && nums[right] == target && nums[right + 1] == target) {
                right = right + 1;
            } else {
                rs[1] = right;
            }
        }
        return rs;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(searchRange(new int[]{3,3,3,3}, 3)));
    }
}
